package com.logistics.controller.tenant;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.logistics.common.Result;
import com.logistics.dto.DispatchArrivalDTO;
import com.logistics.dto.DispatchConfirmDTO;
import com.logistics.dto.DispatchQueryDTO;
import com.logistics.dto.DispatchVehicleInfo;
import com.logistics.entity.Site;
import com.logistics.mapper.SiteMapper;
import com.logistics.service.DispatchRecordService;
import com.logistics.service.DispatchService;
import com.logistics.vo.DispatchVO;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * 发车管理控制器
 */
@RestController
@RequestMapping("/api/tenant/dispatch")
@RequiredArgsConstructor
public class DispatchController {

    @Autowired
    private DispatchService dispatchService;
    
    @Autowired
    private DispatchRecordService dispatchRecordService;

    @Autowired
    private SiteMapper siteMapper;

    /**
     * 获取发车管理数据（待发车和已发车车辆）
     */
    @GetMapping("/vehicles")
    @PreAuthorize("hasAuthority('order:dispatch') or hasAnyRole('SUPER_ADMIN','SITE_ADMIN')")
    public Result<Map<String, List<DispatchVehicleInfo>>> getDispatchVehicles() {
        try {
            Map<String, List<DispatchVehicleInfo>> result = dispatchService.getDispatchVehicles();
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("获取发车数据失败：" + e.getMessage());
        }
    }

    /**
     * 执行发车操作
     */
    @PostMapping("/{vehicleId}")
    @PreAuthorize("hasAuthority('order:dispatch') or hasAnyRole('SUPER_ADMIN','SITE_ADMIN')")
    public Result<String> dispatchVehicle(@PathVariable Long vehicleId) {
        try {
            int affectedOrders = dispatchService.dispatchVehicle(vehicleId);
            return Result.success("发车成功，共发车 " + affectedOrders + " 个订单");
        } catch (Exception e) {
            return Result.error("发车失败：" + e.getMessage());
        }
    }

    /**
     * 撤销发车操作
     */
    @PostMapping("/{vehicleId}/cancel")
    @PreAuthorize("hasAuthority('order:dispatch:cancel') or hasAnyRole('SUPER_ADMIN','SITE_ADMIN')")
    public Result<String> cancelDispatch(@PathVariable Long vehicleId) {
        try {
            int affectedOrders = dispatchService.cancelDispatch(vehicleId);
            return Result.success("撤销发车成功，共撤销 " + affectedOrders + " 个订单");
        } catch (Exception e) {
            return Result.error("撤销发车失败：" + e.getMessage());
        }
    }

    // ==================== 新的发车记录管理接口 ====================
    
    /**
     * 分页查询发车记录
     */
    @PostMapping("/list")
    @PreAuthorize("hasAuthority('order:dispatch') or hasAnyRole('SUPER_ADMIN','SITE_ADMIN')")
    public Result<Page<DispatchVO>> getDispatchList(@RequestBody DispatchQueryDTO query) {
        Page<DispatchVO> result = dispatchRecordService.getDispatchPage(query);
        return Result.success(result);
    }
    
    /**
     * 创建发车记录
     */
    @PostMapping("/create")
    @PreAuthorize("hasAuthority('order:dispatch') or hasAnyRole('SUPER_ADMIN','SITE_ADMIN')")
    public Result<Void> createDispatch(
        @RequestParam Long vehicleId,
        @RequestParam Long departureSiteId,
        @RequestParam Long arrivalSiteId,
        @RequestParam(required = false) String remark
    ) {
        // 查询站点名称
        Site departureSite = siteMapper.selectById(departureSiteId);
        Site arrivalSite = siteMapper.selectById(arrivalSiteId);
        
        if (departureSite == null || arrivalSite == null) {
            return Result.error("站点不存在");
        }
        
        dispatchRecordService.createDispatch(vehicleId, departureSiteId, departureSite.getSiteName(),
            arrivalSiteId, arrivalSite.getSiteName(), remark);
        return Result.success();
    }
    
    /**
     * 为临时车辆创建发车记录
     */
    @PostMapping("/create-temp")
    @PreAuthorize("hasAuthority('order:dispatch') or hasAnyRole('SUPER_ADMIN','SITE_ADMIN')")
    public Result<Void> createTempDispatch(
        @RequestParam String vehiclePlate,
        @RequestParam String vehicleType,
        @RequestParam Long departureSiteId,
        @RequestParam Long arrivalSiteId,
        @RequestParam(required = false) String driverName,
        @RequestParam(required = false) String driverPhone,
        @RequestParam(required = false) String remark
    ) {
        // 查询站点名称
        Site departureSite = siteMapper.selectById(departureSiteId);
        Site arrivalSite = siteMapper.selectById(arrivalSiteId);
        
        if (departureSite == null || arrivalSite == null) {
            return Result.error("站点不存在");
        }
        
        dispatchRecordService.createTempDispatch(vehiclePlate, vehicleType, 
            departureSiteId, departureSite.getSiteName(),
            arrivalSiteId, arrivalSite.getSiteName(),
            driverName, driverPhone, remark);
        return Result.success();
    }
    
    /**
     * 确认发车
     */
    @PostMapping("/confirm")
    @PreAuthorize("hasAuthority('order:dispatch') or hasAnyRole('SUPER_ADMIN','SITE_ADMIN')")
    public Result<Void> confirmDispatch(@Valid @RequestBody DispatchConfirmDTO dto) {
        dispatchRecordService.confirmDispatch(dto);
        return Result.success();
    }
    
    /**
     * 确认到达
     */
    @PostMapping("/arrive")
    @PreAuthorize("hasAuthority('order:dispatch') or hasAnyRole('SUPER_ADMIN','SITE_ADMIN')")
    public Result<Void> confirmArrival(@Valid @RequestBody DispatchArrivalDTO dto) {
        dispatchRecordService.confirmArrival(dto);
        return Result.success();
    }
    
    /**
     * 删除发车记录（物理删除，仅待发车状态）
     */
    @DeleteMapping("/delete/{dispatchId}")
    @PreAuthorize("hasAuthority('order:dispatch:delete') or hasAnyRole('SUPER_ADMIN','SITE_ADMIN')")
    public Result<Void> deleteDispatchRecord(@PathVariable Long dispatchId) {
        dispatchRecordService.deleteDispatch(dispatchId);
        return Result.success();
    }
    
    /**
     * 取消发车记录（状态变更，仅已发车状态）
     */
    @PostMapping("/cancel/{dispatchId}")
    @PreAuthorize("hasAuthority('order:dispatch:cancel') or hasAnyRole('SUPER_ADMIN','SITE_ADMIN')")
    public Result<Void> cancelDispatchRecord(
        @PathVariable Long dispatchId,
        @RequestParam String cancelReason
    ) {
        dispatchRecordService.cancelDispatch(dispatchId, cancelReason);
        return Result.success();
    }
    
    /**
     * 查看车辆订单
     */
    @GetMapping("/vehicle/{vehicleId}/orders")
    @PreAuthorize("hasAuthority('order:view') or hasAnyRole('SUPER_ADMIN','SITE_ADMIN')")
    public Result<List<?>> getVehicleOrders(@PathVariable Long vehicleId) {
        List<?> orders = dispatchRecordService.getVehicleOrders(vehicleId);
        return Result.success(orders);
    }
}
